<?php

namespace App\Http\Controllers\Admin\System;

use App\Http\Controllers\Admin\BaseController;
use App\Http\Requests\Admin\System\RoleSaveFormRequest;
use App\Repositories\System\RoleRepository;
use App\Utils\Output;
use App\Utils\ViewHelper;
use Illuminate\Contracts\Foundation\Application;
use Illuminate\Contracts\View\Factory;
use Illuminate\Contracts\View\View;
use Illuminate\Http\Request;

class RoleController extends BaseController
{
    public function __construct()
    {
        $this->set('system/role');
    }

    function index()
    {
        return $this->view('index');
    }

    function pager(RoleRepository $rep, Request $request)
    {
        return $rep->adminPager($request->all());
    }

    function create()
    {
        return $this->view('create');
    }

    function save(RoleSaveFormRequest $request, RoleRepository $repository)
    {
        $data = $request->all();
        return $repository->save($data, 0);
    }

    function update(RoleSaveFormRequest $request, RoleRepository $repository)
    {
        $data = $request->all();
        $id = $request->get('id', 0);
        return $repository->save($data, $id);
    }

    function edit($id, RoleRepository $repository)
    {
        $result = $repository->detail($id);
        if ($result->isSuccess()) {
            return $this->view('edit')->with('entity', $result->data);
        }
        return ViewHelper::E404($result->msg);
    }

    function batchDelete(Request $request, RoleRepository $repository)
    {
        return $repository->batchDelete($request->post('ids', ''));
    }

    function delete(Request $request, RoleRepository $repository)
    {
        return $repository->delete($request->post('id', ''));
    }


    /**
     * 权限
     * @param int $id
     * @param RoleRepository $repository
     * @return Application|Factory|View|mixed
     */
    public function permission_view(int $id, RoleRepository $repository)
    {
        $permissions = $repository->allPermissions($id)->data;
        return view('admin/system/group/permission', compact('permissions', 'id'))->with('baseRoute', $this->routePrefix . '/');
    }

    /**
     * @param RoleRepository $repository
     * @param Request $request
     * @return Output
     */
    public function permission(RoleRepository $repository, Request $request)
    {
        return $repository->savePermission($request->post());
    }

    function load(RoleRepository $rep, Request $request)
    {
        return $rep->load($request->all());
    }
}
